using B.S.BasicData.EroorCode;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Text;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.Fonts;

namespace B.S.BasicData.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CaptchaController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetCaptcha([FromQuery] Guid? guid)
        {
            var captchaGuid = guid ?? Guid.NewGuid();
            var code = GenerateCaptchaCode(4);
            var imageBytes = GenerateCaptchaImage(code);
            // 可选：将验证码与guid存储到缓存，便于后续校验
            Response.Headers.Add("Captcha-Guid", captchaGuid.ToString());
            Response.Headers.Add("Captcha-Code", code); // 实际生产环境不要返回code，仅用于演示
            return File(imageBytes, "image/png");
        }

        private string GenerateCaptchaCode(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            var sb = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                sb.Append(chars[random.Next(chars.Length)]);
            }
            return sb.ToString();
        }

        private byte[] GenerateCaptchaImage(string code)
        {
            int width = 120;
            int height = 40;
            using var image = new Image<Rgba32>(width, height);
            image.Mutate(ctx =>
            {
                ctx.Fill(Color.White);
                var font = SystemFonts.CreateFont("Arial", 24, FontStyle.Bold);
                ctx.DrawText(code, font, Color.Black, new PointF(10, 5));
            });
            using var ms = new MemoryStream();
            image.SaveAsPng(ms);
            return ms.ToArray();
        }
    }
} 